<?php

class Database {

	// Function to the database and tables and fill them with the default data
	function create_database($data)
	{
		// Connect to the database
		$mysqli = new mysqli($data['hostname'],$data['username'],$data['password'],'');

		// Check for errors
		if(mysqli_connect_errno())
			return false;

		// Create the prepared statement
		$mysqli->query("CREATE DATABASE IF NOT EXISTS ".$data['database']);

		// Close the connection
		$mysqli->close();

		return true;
	}

	// Function to create the tables and fill them with the default data
	function create_tables($data)
	{
		// Connect to the database
		$mysqli = new mysqli($data['hostname'],$data['username'],$data['password'],$data['database']);
		$mysqli->set_charset("utf8");
		// Check for errors
		if(mysqli_connect_errno())
			return false;

		// Open the default SQL file
		$query = file_get_contents('assets/install.sql');

		$query = str_replace('%DBPREFIX%', $data['database_prefix'], $query);

		$querys = explode(';',$query);

		foreach($querys as $q)
		{
			$mysqli->query($q);
		}

		// Close the connection
		$mysqli->close();

		return true;
	}

	function list_tables($data)
	{
		$mysqli = new mysqli($data['hostname'],$data['username'],$data['password'],$data['database']);
		
		$result = $mysqli->query("SHOW TABLES");

		while($t = $result->fetch_array())
		{
			$tables[] = $t[0];
		}

		return $tables;
	}
}